local cid = arg[1] or "asr1"
--是否为常驻asrclient，不是的话，一段时间没有任务就会自动退出
local isResident = arg[2] or true;

local cjson = require "cjson"
local socket = require("socket")
local tcp = assert(socket.tcp())

local host, port = "127.0.0.1", 8080

INIT_DATE = [[
{"sender":"asrclient","msgtype":"init","cid":"_cid_"}
]]

ASR_DATA = [[
{"sender":"asrclient","msgtype":"asresponse","data":"_data_","cid":"_cid_", "tocid":"_tocid_"}
]]

function sleep(n)
  os.execute("sleep " .. tonumber(n))
end

function log(loglevel, content)
    if loglevel == "info" then
        print(content)
    end
end

--received: {"sender":"client","msgtype":"asrequest","cid":"xx_yy_zz", "data":"xxx.wav"}
--send: "sender":"asrclient","msgtype":"asresponse","data":"你好","cid":"222", "tocid":"xx_yy_zz"}
function parseAsr(msg)
	local crt, data = pcall(cjson.decode, msg);
    if crt then
    	ASR_DATA1 = string.gsub(ASR_DATA,  "_cid_", cid);
    	ASR_DATA1 = string.gsub(ASR_DATA1,  "_tocid_", data["cid"]);
    	ASR_DATA1 = string.gsub(ASR_DATA1,  "_data_", "你好");
    	return ASR_DATA1;
    end
    log("debug","非法的消息体{" .. msg .. "}")
end

do
    log("debug","cid:" .. cid)
    tcp:connect(host, port);
    log("debug","ready to send:{" .. INIT_DATE .. "}")
    local myInit = string.gsub(INIT_DATE, "_cid_", cid);
    tcp:send(myInit);

    log("debug","start to receive:")
    while true do
        local recvMsg, status, partial = tcp:receive()
        log("debug","receive:" .. (recvMsg or ""))
        if status == "closed" then 
            break 
        end


        sleep(10);

        local resp = parseAsr(recvMsg);
        log("debug","ready to send response:{" .. resp .. "}")
        tcp:send(resp);
    end
    tcp:close()
end